﻿using MoLingOverhaul.Common.Cores.Enum;
using System;
using Terraria.Localization;
using Terraria.ModLoader.IO;

namespace MoLingOverhaul.Common.Cores.Data
{
    public class SeasonData
    {
        public Season CurrentSeason { get; set; } = Season.Spring;
        public int DaysInCurrentSeason { get; set; } = 0;
        public int TotalDays { get; set; } = 0;
        public int SeasonLength => 12;
        public int FullCycleLength => SeasonLength * 4;
        public float SeasonProgress => (float)DaysInCurrentSeason / SeasonLength;
        public float CycleProgress => (float)(TotalDays % FullCycleLength) / FullCycleLength;
        public void UpdateSeason()
        {
            TotalDays++;
            DaysInCurrentSeason++;
            if (DaysInCurrentSeason >= SeasonLength)
            {
                DaysInCurrentSeason = 0;
                CurrentSeason = GetNextSeason(CurrentSeason);
                OnSeasonChanged?.Invoke(CurrentSeason);
            }
        }
        private static Season GetNextSeason(Season current)
        {
            return current switch
            {
                Season.Spring => Season.Summer,
                Season.Summer => Season.Autumn,
                Season.Autumn => Season.Winter,
                Season.Winter => Season.Spring,
                _ => Season.Spring
            };
        }
        public event Action<Season> OnSeasonChanged;
        public string GetSeasonName()
        {
            return CurrentSeason switch
            {
                Season.Spring => Language.GetTextValue("Mods.MoLingOverhaul.UI.7"),
                Season.Summer => Language.GetTextValue("Mods.MoLingOverhaul.UI.8"),
                Season.Autumn => Language.GetTextValue("Mods.MoLingOverhaul.UI.9"),
                Season.Winter => Language.GetTextValue("Mods.MoLingOverhaul.UI.10"),
                _ => Language.GetTextValue("Mods.MoLingOverhaul.UI.11")
            };
        }      
        public TagCompound Save()
        {
            return new TagCompound
            {
                ["TotalDays"] = TotalDays,
                ["CurrentSeason"] = (int)CurrentSeason,
                ["DaysInCurrentSeason"] = DaysInCurrentSeason
            };
        }
        public void Load(TagCompound tag)
        {
            if (tag.ContainsKey("TotalDays"))
            {
                TotalDays = tag.GetInt("TotalDays");
                CurrentSeason = (Season)tag.GetInt("CurrentSeason");
                DaysInCurrentSeason = tag.GetInt("DaysInCurrentSeason");
            }
        }       
    }
}